package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.api.user.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.*;
import com.jmp.im.ImNotifyClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.mapper.CardCacheModel;
import one.stand.mapper.DynamicApiUserMapper;
import one.stand.mapper.GoodsApiUserMapper;
import one.stand.mapper.SeeDetailApiUserMapper;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.CallsPhoneRecordRequest;
import one.stand.request.CompanyRequest;
import one.stand.request.SeeRecordRequest;
import one.stand.response.BusinessCardResponse;
import one.stand.response.CompanyResponse;
import one.stand.service.*;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("userApi/businessCard")
@Api(description = "名片系列")
public class BusinessCardController extends BaseController {
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;
    @Autowired
    private CompanyFeign companyFeign;
    @Autowired
    private CardFeign cardFeign;
    @Autowired
    private RecordFeign recordFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private TemplateFeign templateFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private MessageMsgService messageMsgService;
    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private CompanyShowroomService companyShowroomService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GoodsApiUserMapper goodsApiUserMapper;
    @Autowired
    private DynamicApiUserMapper dynamicApiUserMapper;
    @Autowired
    private SeeDetailApiUserMapper seeDetailApiUserMapper;

    @ApiOperation(value = "得到登录人的公司id")
    @PostMapping("getCompanyId")
    @SecurityAuthCheck
    public ResultModel<CompanyResponse> getCompanyId(@RequestAttribute CompanyRequest request) {
        return crmFegin.getCompanyId(request);
    }

    @PostMapping("seeDetail")
    @ApiOperation(value = "查看名片列表")
    @SecurityAuthCheck
    public ResultModel<List<CardListResponse>> seeDetail(@RequestAttribute CardListRequest request) {
        // 查询是否对默认名片有查看记录，如果没有就需要查询默认名片
//        int num = seeDetailApiUserMapper.isHaveDefaultCard(request.getCompanyKey(), request.getId());
//        Integer type = num <= 0 ? 1 : null;
        SysDictValue sysDictValue = sysDictValueService.get(SysDictValueService.Type.default_company_key, SysDictValueService.TypeName.default_company_key);
        final boolean isDefaultPlatform = sysDictValue.getValue().equals(request.getCompanyKey());
        final String companyKey = isDefaultPlatform ? null : request.getCompanyKey();

        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CardListResponse> response = seeDetailApiUserMapper.selectSeeList(null, companyKey, request.getId(), nameLike);
        if (OneListUtil.isEmpty(response) && request.getPageNum() == 1) {
            response = seeDetailApiUserMapper.selectDefault(request.getCompanyKey(), nameLike);
        }

        return ResultModel.success(response);
    }

    @PostMapping("updateCard")
    @ApiOperation(value = "修改名片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "style", value = "名片样式", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "name", value = "姓名", paramType = "String"),
            @ApiImplicitParam(name = "phone", value = "电话", paramType = "String"),
            @ApiImplicitParam(name = "logo", value = "头像url", paramType = "String"),
            @ApiImplicitParam(name = "personalWx", value = "个人微信", paramType = "String"),
            @ApiImplicitParam(name = "companyWx", value = "公司微信", paramType = "String"),
            @ApiImplicitParam(name = "photo", value = "个人照片集合（1.png,2.png,3.png）", paramType = "String"),
            @ApiImplicitParam(name = "position", value = "职位", paramType = "String"),
            @ApiImplicitParam(name = "soundRecording", value = "个人录音", paramType = "String"),
            @ApiImplicitParam(name = "soundTime", value = "录音时长", paramType = "Integer"),
            @ApiImplicitParam(name = "email", value = "邮箱", paramType = "String"),
            @ApiImplicitParam(name = "briefIntroduction", value = "个人简介", paramType = "String"),
    })
    @SecurityAuthCheck
    public ResultModel<Boolean> updateCard(@RequestAttribute BusinessCardRequest request) {
        return userFegin.updateCard(request);
    }

    @PostMapping("cardDetails")
    @ApiOperation(value = "名片详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "refresh", value = "刷新进入传1", paramType = "String"),
    })
    @SecurityAuthCheck
    public ResultModel<BusinessCardResponse> cardDetails(@RequestAttribute CardDetailRequest request) {
        AssertUtil.nonNull(request, ResultEnum.NO_PARAM);

        BusinessCard outModel;
        if (request.getUserId() != null) {// 根据userid获取名片信息
            outModel = businessCardBaseService.getByUserId(request.getUserId());
            if (!(outModel != null && outModel.getCardId() != null)) {
                AssertUtil.nonNull(outModel, ResultEnum.PARAM_CHECK, "对方尚未注册企业或已解散！");
                BusinessCardResponse response = new BusinessCardResponse();
                copyProperties(outModel, response);
                return ResultModel.success(response);
            }
        } else {
            outModel = businessCardBaseService.getCustomer(request.getCardId());
        }
        AssertUtil.isFalse(outModel == null || outModel.getIsDel() != 0 || outModel.getState() != 1, ResultEnum.FAIL);

        request.setCardId(outModel.getCardId());
        BusinessCardResponse response = cardDetail(outModel);

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        // 是否点赞
        response.setIsThumbs(BooleanUtils.toInteger(recordPublicService.isThumbs(optUser.getUserId(), RecordPublicService.THUMBS_TYPE_CARD, request.getCardId())));

        response.setCardType(0);// 0 自己名片
        if (!RequestContextHolder.getRequestContext().isSelf(outModel.getUserId())) {//验证是否是查看登录人自己的名片
            response.setCardType(1);// 1 他人名片，未存为客户

            if (Objects.nonNull(optUser.getCompanyId())) {
                BusinessCardModel businessCardModel = businessCardBaseService.getCustomer(outModel.getPersonalWx(), outModel.getPhone(), optUser.getCompanyId(), null);
                if (Objects.nonNull(businessCardModel)) {
                    response.setCardType(2);// 2 已存为客户
                }
            }

            //添加查看记录
            SeeRecordCardRequest seeRecordCardRequest = SeeRecordCardRequest.builder()
                    .userId(optUser.getUserId())
                    .cardId(request.getCardId())
                    .itemId(request.getCardId())
                    .isWechat(!"1".equals(request.getRefresh()))
                    .build();
            seeRecordFeign.card(seeRecordCardRequest);
        }

        Integer unReadMsg = messageMsgService.getUnreadNum(String.valueOf(optUser.getUserId()), String.valueOf(outModel.getUserId()), ImNotifyClient.TYPE);
        response.setUnReadMsg(unReadMsg);

        return ResultModel.success(response);
    }

    @ApiOperation(value = "名片置顶")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordId", value = "名片记录id", required = true, paramType = "Integer"),
    })
    @PostMapping("isTop")
    @SecurityAuthCheck
    public ResultModel<Boolean> isTop(@RequestAttribute SeeRecordRequest request) {
        BusinessCard outModel = businessCardBaseService.getCustomer(request.getCardId());

        SeeRecordCardRequest seeRecordCardRequest = SeeRecordCardRequest.builder()
                .userId(request.getId().intValue())
                .cardId(request.getCardId())
                .itemId(request.getCardId())
                .isWechat(false)
                .build();
        seeRecordFeign.card(seeRecordCardRequest);
        return ResultModel.success(true);
    }

    @ApiOperation(value = "查询用户自己的名片")
    @PostMapping("getUserCard")
    @SecurityAuthCheck
    public ResultModel<BusinessCardResponse> getUserCard(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        BusinessCard businessCardModel = businessCardBaseService.getByUserId(optUser.getUserId());
        AssertUtil.nonNull(businessCardModel, "名片不存在");

        Integer userId = Objects.nonNull(request.getUserId()) ? request.getUserId() : optUser.getUserId();
        Company company = companyBaseService.getById(businessCardModel.getCompanyId());

        BusinessCardResponse response = new BusinessCardResponse();
        BeanUtils.copyProperties(businessCardModel, response);
        response.setBrowseNum(businessCardModel.getSeeNum());
        response.setIsThumbs(BooleanUtils.toInteger(recordPublicService.isThumbs(userId, RecordPublicService.THUMBS_TYPE_CARD, request.getCardId())));
        response.setCompanyName(company.getCompanyName());
        response.setCompanyLogo(company.getCompanyLogo());
        return ResultModel.success(response);
    }

    @ApiOperation(value = "删除浏览记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("delSeeCard")
    @SecurityAuthCheck
    public ResultModel delSeeCard(@RequestAttribute SeeRecordRequest request) {
        ResultModel resultModel = seeRecordFeign.remove(SeeRecordRemoveDto.builder()
                .userId(request.getId().intValue())
                .cardId(request.getCardId())
                .build());
        AssertUtil.isTrue(resultModel);
        return ResultModel.success();
    }

    @ApiOperation(value = "点赞操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("doThumbs")
    @SecurityAuthCheck
    public ResultModel doThumbs(@RequestAttribute SeeRecordRequest request) {
        if (null == request || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }

        userFeign.thumbs(UserThumbsDto.builder()
                .itemType(RecordPublicService.THUMBS_TYPE_CARD)
                .itemId(request.getCardId())
                .userId(request.getId().intValue())
                .build());
        return ResultModel.success();
    }

    @ApiOperation(value = "得到名片二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("getWxTwoCode")
    @SecurityAuthCheck
    public ResultModel getWxTwoCode(@RequestAttribute BusinessCardRequest request) {
        SunCodeCardRequest sunCodeCardRequest = SunCodeCardRequest.builder().cardId(request.getCardId()).build();
        ResultModel<SunCodeCardResponse> sunCodeCardResponseResultModel = sunCodeFeign.card(sunCodeCardRequest);
        AssertUtil.isTrue(sunCodeCardResponseResultModel);
        String wxTwoCode = sunCodeCardResponseResultModel.getData().getCodeUrl();
        return ResultModel.success(wxTwoCode);
    }

    @ApiOperation(value = "添加通话记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "被拨打人名片id", required = true, paramType = "Integer"),
    })
    @PostMapping("addCallsRecord")
    @SecurityAuthCheck
    public ResultModel addCallsRecord(@RequestAttribute CallsPhoneRecordRequest request) {
        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        ResultModel resultModel = recordFeign.call(RecordCallRequest.builder().userId(user.getUserId()).cardId(request.getCardId()).build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success(true);
    }

    @ApiOperation(value = "验证名片是否过期")
    @PostMapping("/verifyExpired")
    @SecurityAuthCheck
    public ResultModel<Long> verifyExpired(@RequestAttribute CardVerifyExpiredRequest request) {
        ResultModel<CardCheckResponse> cardCheckResponseResultModel = cardFeign.check(CardCheckRequest.builder().cardId(request.getCardId()).build());
        AssertUtil.isTrue(cardCheckResponseResultModel);
        AssertUtil.isTrue(cardCheckResponseResultModel.getData().isEffective(), "名片已过期");
        return ResultModel.success(cardCheckResponseResultModel.getData().getDays());
    }

    @PostMapping("getCardPoster")
    @ApiOperation(value = "得到名片海报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardId", value = "名片id", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck(card = true)
    public ResultModel getCardPoster(@RequestAttribute BusinessCardRequest request) {
        return crmFegin.getCardPoster(request);
    }

    private BusinessCardResponse cardDetail(BusinessCard outModel) {
        CardCacheModel cardCacheModel = new CardCacheModel(redisUtil, outModel.getCardId());
        BusinessCardResponse response = cardCacheModel.get();
        if (Objects.nonNull(response)) return response;

        response = new BusinessCardResponse();
        copyProperties(outModel, response);

        response.setThumbsNum(recordPublicService.getThumbsCount(RecordPublicService.THUMBS_TYPE_CARD, outModel.getCardId()));
        response.setBrowseNum(outModel.getSeeNum());
        List<String> photos = seeDetailApiUserMapper.selectCardPhoto(outModel.getCardId());
        if (OneListUtil.isNotEmpty(photos)) {
            response.setBrowsePhoto(String.join(",", photos));
        }

        //公司信息
        Company companyModel = companyBaseService.getById(outModel.getCompanyId());
        response.setCompanyName(companyModel.getCompanyName());
        response.setCompanyLogo(companyModel.getCompanyLogo());
//        response.setIsAgent(companyModel.getIsAgent());
        response.setShowRoomState(CompanyBaseService.SHOWROOMSTATE_OPEN.equals(companyModel.getShowroomstate()));

        // 公司地址
        Website websiteModel = websiteService.getByCompanyId(outModel.getCompanyId());
        if (null != websiteModel) {
            response.setAddress(websiteModel.getAddress());
            response.setLatitude(websiteModel.getLatitude());
            response.setLongitude(websiteModel.getLongitude());
        }

        //分享海报
        TemplateGet2Request createRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_WECHAT_CARD)
                .cardId(outModel.getCardId())
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(createRequest);
        AssertUtil.isTrue(getResponseResultModel);
        response.setShareCardUrl(getResponseResultModel.getData().getImageUrl());

        cardCacheModel.save(response);
        return response;
    }

    @ApiOperation(value = "名片详情首页")
    @PostMapping("/index")
    @SecurityAuthCheck
    public ResultModel<CardIndexResponse> index(@RequestAttribute CardIndexRequest request) {
        BusinessCard businessCard = businessCardBaseService.getCustomer(request.getCardId());
        AssertUtil.nonNull(businessCard, ResultEnum.PARAM_CHECK);
        request.setCardId(businessCard.getCardId());

        //主推商品
        List<Goods> mainPush = goodsApiUserMapper.selectMainPush(businessCard.getCompanyId());
        List<CardIndexResponse.Goods> mainGoodsList = ConvertUtils.list(mainPush, goods -> CardIndexResponse.Goods.builder()
                .goodsId(goods.getGoodsId())
                .name(goods.getGoodsName())
                .pic(goodsPhotoService.getPath(goods.getGoodsId()))
                .build());

        //每日精选
        List<Goods> daySelect = goodsApiUserMapper.selectDaySelect(businessCard.getCompanyId());
        List<CardIndexResponse.Goods> dayGoodsList = ConvertUtils.list(daySelect, goods -> CardIndexResponse.Goods.builder()
                .goodsId(goods.getGoodsId())
                .name(goods.getGoodsName())
                .pic(goodsPhotoService.getPath(goods.getGoodsId()))
                .build());
        if (OneListUtil.isEmpty(mainGoodsList) && OneListUtil.isNotEmpty(dayGoodsList)) {
            if (dayGoodsList.size() > 3) {
                mainGoodsList = dayGoodsList.subList(0, 3);
            } else {
                mainGoodsList = dayGoodsList;
            }
        }

        //热门动态
        List<Dynamic> dynamics = dynamicApiUserMapper.selectHot(businessCard.getCompanyId(), businessCard.getUserId());
        List<CardIndexResponse.Dynamic> hotDynamicList = ConvertUtils.list(dynamics, dynamic -> CardIndexResponse.Dynamic.builder()
                .id(dynamic.getDynamicId())
                .title(dynamic.getTitle())
                .pic(getOne(dynamic.getPhotos()))
                .build());

        //3d
        CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(businessCard.getCompanyId());

        CardIndexResponse response = CardIndexResponse.builder()
                .mainGoodsList(mainGoodsList)
                .dayGoodsList(dayGoodsList)
                .dynamicList(hotDynamicList)
                .vrUrl(Objects.nonNull(companyShowroom) ? companyShowroom.getVrUrl() : null)
                .build();
        return ResultModel.success(response);
    }

    private String getOne(String photos) {
        if (StringUtils.isBlank(photos)) return photos;
        String[] photoArr = photos.split(",");
        return photoArr[0];
    }
}
